<?php

/**
 * 每天定时查看，公司提现申请单，如果已经提交35天，还未入账，则本次申请单失效，并返回提现金额到公司账户可申请提现金额。下次提交申请中可以提取
 * @author tangyiwan
 */


ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\model\salesRebate\SalesWithdrawalRecord as mSalesWithdrawalRecord;
use Biz\model\salesRebate\SalesAccount as mSalesAccount;
use Medoo\Medoo;
use Biz\model\salesRebate\SalesAccountLog as mSalesAccountLog;


$type = mSalesWithdrawalRecord::TYPE_COMPANY;
$time = date('Y-m-d H:i:s', strtotime('-35 days'));
$withdrawalRecordList = mSalesWithdrawalRecord::getAllByWhere('*', ['type' => $type, 'status[<]' => mSalesWithdrawalRecord::STATUS_ACCOUNTED,'addtime[<]'=>$time]);
try {
    $result = mSalesAccount::action(function () use ($type, $withdrawalRecordList) {
        if ($withdrawalRecordList) {//存在未入账的，则需要把申请单置为失效状态，同时，退换提现金额到用户账户可提现金额当中
            foreach ($withdrawalRecordList as $row) {
                $accountInfo = mSalesAccount::select_master("*", Medoo::raw(' where uid=:uid and type=:type for update', [':uid' => $row['uid'], ':type' => $type]));
                $accountInfo = array_shift($accountInfo);
                $withdrawalAmount = $row['withdrawal_amount'];
                $result = mSalesWithdrawalRecord::updateData(['status' => mSalesWithdrawalRecord::STATUS_INVALID], ['id' => $row['id']]);
                if ($result) {
                    $logArr = [
                        'operate_type' => mSalesAccountLog::OPERATE_TYPE_WITHDRAWAL_INVALID,
                        'operate_user_type' => mSalesAccountLog::OPERATE_USER_TYPE_SYS,
                        'operate_user_id' => 0,
                        'withdrawal_code' => $row['withdrawal_code'],
                    ];
                    $result = mSalesAccount::updateAccount($accountInfo, $row['uid'], $type, $withdrawalAmount, 0, $logArr, 0);
                    if (!$result) {
                        throw new \Exception('更新公司账户可提现金额失败');
                    }
                } else {
                    throw new \Exception('发现有未入账的公司提现申请单，需要置为失效，但更新失败');
                }
            }
        }
        return true;
    });
} catch (\Exception $e) {
    $msg = '检查公司提现申请单是否有未入账记录失败#' . '#$withdrawal_record_list:' . json_encode($withdrawalRecordList, JSON_UNESCAPED_UNICODE) . '#msg:' . json_encode([
            'e_file' => $e->getFile(),
            'e_line' => $e->getLine(),
            'e_msg' => $e->getMessage()
        ], JSON_UNESCAPED_UNICODE);
    Queue::insertQueue("queue/Wechatnotice/toTag", [
        "totag" => \Biz\pockets\constInterface\BizWechatTagConfig::TAG_BIZ_RD_SYSTEM,
        "content" => $msg
    ], Queue::QUEUE_BIZ);
    Log::debug($msg);
    return false;
}







